<template>
  <div>
    <el-button type="primary" size="large" @click="handleSetHeader">
      <i-ep-Setting></i-ep-Setting>
      设置表头
    </el-button>
    <UploadFile
      @startHandle="startHandle"
      @fileUpload="fileUpload"
    ></UploadFile>

    <el-button
      type="success"
      size="large"
      :loading="loading"
      @click="handleDownload"
    >
      <i-ep-Upload></i-ep-Upload>
      生成Excel文件
    </el-button>
    <el-button
      type="warning"
      size="large"
      :loading="loading"
      @click="handleDownloadJson"
    >
      <i-ep-Upload></i-ep-Upload>
      生成JSON文件
    </el-button>
    <el-button
      type="danger"
      size="large"
      :loading="loading"
      @click="handleDelete"
    >
      <i-ep-Delete></i-ep-Delete>
      删除
    </el-button>
    <el-button
      type="danger"
      size="large"
      :loading="loading"
      @click="resetDataBase"
    >
      <i-ep-Delete></i-ep-Delete>
      重置数据库
    </el-button>
    <el-table
      :data="tableData"
      :border="true"
      stripe
      style="width: 100%"
      v-loading="loading"
      height="500px"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection"> </el-table-column>
      <el-table-column
        v-for="item in colums"
        :key="item.prop"
        :prop="item.prop"
        :label="item.label"
        :width="item.width"
      >
      </el-table-column>
    </el-table>
    <div style="padding-top: 15px">
      <el-input
        type="textarea"
        v-model="textAreaValue"
        :rows="15"
        clearable
        resize="none"
      ></el-input>
    </div>
    <CustomRelation v-model:dialogVisible="dialogVisible"></CustomRelation>
  </div>
</template>

<script lang="ts" setup>
import type { Results, Rack } from '@/hooks/types'
import { getInstance } from '@/utils/tool'
import { useDownloadExcel } from '@/hooks/use-excel'
import { ElMessage } from 'element-plus'
import UploadFile from './UploadFile.vue'
import { exportJson } from '@/utils/tool'
import { useAnalysisStore } from '@/stores/index'
import CustomRelation from './CustomRelation.vue'

// 获取excel的store
const analysisStore = useAnalysisStore()
const dialogVisible = ref<boolean>(false)
function handleSetHeader() {
  dialogVisible.value = true
}

const colums = ref(getColums())
// 订阅pinia状态变化
analysisStore.$subscribe(() => {
  colums.value = getColums()
})
// 获取表头
function getColums() {
  return Object.entries(analysisStore.excelMapState).map(([key, value]) => {
    return {
      prop: key,
      label: value,
      width: '180'
    }
  })
}

const loading = ref(false)
const textAreaValue = ref('')
const tableData = ref<Results>([])
onMounted(async () => {
  loading.value = true
  const data = await getInstance().queryAll<Rack>({
    tableName: 'Excel_table'
  })
  tableData.value = data.map((item) => {
    delete item.createdTime
    return item
  })
  textAreaValue.value = JSON.stringify(tableData.value)
  loading.value = false
})
// 监听开始处理文件事件
function startHandle() {
  loading.value = true
}
// 监听上传文件事件
async function fileUpload(dataResult: Results) {
  // 导出json
  await getInstance().insert<Rack>({
    tableName: 'Excel_table',
    data: dataResult.map((item) => {
      return {
        ...item,
        createdTime: new Date().getTime()
      }
    })
  })
  tableData.value = await getInstance().queryAll<Rack>({
    tableName: 'Excel_table'
  })
  textAreaValue.value = JSON.stringify(tableData.value)
  loading.value = false
}

let selectRows: Array<Rack> = [] as unknown as Array<Rack>
// 表格复选事件监听
const handleSelectionChange = (row: Array<Rack>) => {
  selectRows = row
}
// 删除
const handleDelete = async () => {
  await getInstance().delete<Rack>({
    tableName: 'Excel_table',
    condition: (item) => selectRows.some((el) => el.id === item.id)
  })
  tableData.value = await getInstance().queryAll<Rack>({
    tableName: 'Excel_table'
  })
}
// 重置数据库
const resetDataBase = async () => {
  const res = await getInstance().delete_db('Excel_DataBase')
  console.log(res)
  ElMessage.success('重置数据库完成！')
}

//生成Excel导出
const handleDownload = () => {
  console.log('导出excel')
  useDownloadExcel({
    header: Object.values(analysisStore.excelMapState), // 表格的头部是一个数组
    // multiHeader,
    // merges,
    data: format2Array(
      tableData.value,
      analysisStore.excelMapState,
      Object.values(analysisStore.excelMapState)
    ),
    filename: '信息表', // 导出的表格文件名
    autoWidth: true, // 宽度自适应
    bookType: 'xlsx'
  })
}
// 处理二维数组的方法
function format2Array(
  rows: Results,
  headersRelations: { [key: string]: string },
  headersArr?: Array<string>
) {
  return rows.map((item) => {
    // item是每一个对象
    const arr: Array<string | number> = []
    if (headersArr) {
      headersArr.forEach((k) => {
        for (const key in headersRelations) {
          if (k === headersRelations[key]) {
            arr.push(item[key])
          }
        }
      })
    } else {
      // 转换二维数组 还要处理中英文对照关系
      for (const [key] of Object.entries(headersRelations)) {
        arr.push(item[key])
      }
    }
    return arr
  })
}
// 生成json文件
const handleDownloadJson = () => {
  exportJson(textAreaValue.value)
}
</script>

<style scoped></style>
